#include "txtbuilder.h"
#include <wx/wx.h>
#include "verinfo.h"

TxtBuilder::TxtBuilder(wxString filename) {
    m_babylonfilename = filename;
    
    file.Open(m_babylonfilename, _T("w+b"));
    
    m_entriescount = 0;
}

TxtBuilder::~TxtBuilder() {
}

bool TxtBuilder::addHeadword(wxString word, wxString def) {
    m_entriescount++;
    
    wxString lines;
    
    int len = word.Len();
    if (word[len-1]=='$') {
        const wxChar *p = word.c_str();
        const wxChar *p1= wxStrchr(p, '$');
        lines.assign(p, p1-p);
    } else {
        lines = word;
    }
    
    lines.Append('\t');
    lines.Append(def);
    lines.Append(_T("\n\n"));
    
    file.Write(lines);
    
    return true;
}

bool TxtBuilder::write_info() {
    file.Write(_T("<dictinfo>\n"));
    
    // file.Write(line);
    
    wxString line = _T("#bookname=");
    line += title;
    line += '\n';
    file.Write(line);
    
    line = _T("#author=");
    line += author;
    line += '\n';
    file.Write(line);
    
    line = _T("#email=");
    line += email;
    line += '\n';
    file.Write(line);
    
    line = _T("#website=");
    line += website;
    line += '\n';
    file.Write(line);
    
    line = _T("#license=");
    line += license;
    line += '\n';
    file.Write(line);
    
    line = _T("#version=");
    line += _T(PRODUCT_VERSION_NUMBER);  // ??
    line += '\n';
    file.Write(line);
    
    line = _T("#description=");
    line += description;
    line += '\n';
    file.Write(line);
    
    line = _T("#origLang=");
    line += origLang;
    line += '\n';
    file.Write(line);
    
    line = _T("#destLang=");
    line += destLang;
    line += '\n';
    file.Write(line);
    
    file.Write(_T("</dictinfo>\n"));
}

bool TxtBuilder::finish() {
    file.Close();
    
    wxPrintf(_T("Default charset: %s\n"
            "Source Charset: %s\n"
            "TargetCharset: %s\n"),
            defaultCharset.c_str(), sourceCharset.c_str(),
            targetCharset.c_str());


    wxPrintf( _T("\nWrite file: %s\n"
            "Word count: %d\n"
            "Bookname: %s\n"
            "Author: %s\n"
            "Email: %s\n"
            "Website: %s\n"
            "License: %s\n"
            "Description: %s\n"
            "Original Language: %s\n"
            "Destination Language: %s\n")
            , m_babylonfilename.c_str()
            , m_entriescount
            , title.c_str()
            , author.c_str()
            , email.c_str()
            , website.c_str()
            , license.c_str()
            , description.c_str()
            , origLang.c_str()
            , destLang.c_str());
        
    return true;
}
